const {resolve} = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const pages = require('./pages.config.js')

let plugins = [];
let entry = {};

pages.forEach(value => {
  if (value.filename) {
    plugins.push(new HtmlWebpackPlugin({
      title: value.title || value.filename.replace('.html', ''),
      template: value.template || undefined,
      filename: value.filename,
      chunks: value.chunks || [value.filename.replace('.html', '')],
      // minify: {collapseWhitespace: true, removeComments: true},
    }))
    entry[value.name || value.filename.replace('.html', '')] = value.entry
  }
})
const active = true // true === dev
webpackConfig = {
  mode: active ? 'development' : 'production',
  devtool: active ? 'source-map' : '',  // 代码调试
  devServer: {contentBase: resolve(__dirname, './gh-pages'), compress: true, host: '0.0.0.0', port: 9090},
  entry,
  output: {
    filename: 'js/[name].js',
    path: resolve(__dirname, './gh-pages'),
    publicPath: '',
    chunkFilename: 'js/chunk_[name].js',
  },
  module: {
    rules: [
      {
        test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader',
          // {loader: 'postcss-loader', options: {ident: 'postcss', plugins: () => [require('postcss-preset-env')()]}}
        ]
      },
      // {
      //   test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: {
      //     presets: [[
      //       '@babel/preset-env', {useBuiltIns: 'usage', corejs: {version: 3}, targets: {chrome: '60', firefox: '50', ie: '9', safari: '10', edge: '17'}}
      //     ]]
      //   }
      // },
      {test: /\.(jpg|png|gif|jpeg|hdr|tif|svg|webp)/, loader: 'url-loader', options: {limit: 8 * 1024, name: '[name].[ext]', outputPath: 'images', esModule: false}},
      {test: /\.(fbx|FBX|glb|gltf)/, loader: 'url-loader', options: {limit: 8 * 1024, name: '[name].[ext]', outputPath: 'models', esModule: false}},
      {test: /\.html$/, loader: 'html-loader'},
      {exclude: /\.(js|css|less|html|jpg|png|gif)/, loader: 'file-loader', options: {outputPath: 'files'}}
    ]
  },
  plugins: [
    ...plugins,
    new MiniCssExtractPlugin({
      filename: 'css/[name].css'
    }),
    new OptimizeCssAssetsWebpackPlugin(),
  ]
}

module.exports = webpackConfig
